<template>
  <!-- 注册页面 -->
  <Vcode
    :show="VcodeShow"
    @success="success"
    @close="close"
    @fail="fail"
  ></Vcode>
  <div class="register">
    <el-form
      ref="registerRef"
      :model="registerForm"
      :rules="registerRules"
      class="register-form"
    >
      <h3 class="title">注册账号</h3>
      <el-form-item prop="phoneNumber">
        <el-input
          v-model="registerForm.phoneNumber"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="手机号"
        >
          <template #prefix
            ><svg-icon icon-class="user" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="smsCode">
        <div class="inputButton">
          <el-input
            v-model="registerForm.smsCode"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="验证码"
          >
            <template #prefix
              ><svg-icon icon-class="user" class="el-input__icon input-icon"
            /></template>
          </el-input>
          <el-button
            class="CodeButton"
            size="large"
            @click="giveCode"
            :disabled="num != 0"
            >{{ num == 0 ? "获取验证码" : `${num}秒后重新发送` }}</el-button
          >
        </div>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleRegister"
        >
          <template #prefix
            ><svg-icon icon-class="password" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter="handleRegister"
        >
          <template #prefix
            ><svg-icon icon-class="password" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="registerForm.x"
          label=""
          true-label="1"
          false-label="2"
        />
        <el-link>&nbsp;我已阅读并同意《xxx》</el-link>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleRegister"
        >
          <span v-if="!loading">下 一 步</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right">
          <router-link class="link-type" :to="'/login'"
            >使用已有账户登录</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-register-footer">
      <span>Sparke V1.0.0</span>
    </div>
  </div>
</template>

<script setup>
import {
  getCodeAPI,
  checkSmsCodeAPI,
  phoneRegisterAPI,
} from "@/api/system/user.js";
import { ElMessageBox } from "element-plus";
import { getCodeImg, register } from "@/api/login";
import Vcode from "vue3-puzzle-vcode";
const router = useRouter();
const { proxy } = getCurrentInstance();
const VcodeShow = ref(false); //图片滑块验证码
const registerRef = ref(null);
const registerForm = ref({
  phoneNumber: "",
  password: "",
  confirmPassword: "",
  smsCode: "",
  uuid: "",
  x: "",
});
const num = ref("");

const equalToPassword = (rule, value, callback) => {
  if (registerForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const registerRules = {
  phoneNumber: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入您的密码" },
    {
      min: 5,
      max: 20,
      message: "用户密码长度必须介于 5 和 20 之间",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" },
  ],
  smsCode: [{ required: true, trigger: "change", message: "输入您的验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
const captchaEnabled = ref(true);

function handleRegister() {
  if (registerForm.value.x != "1")
    return proxy.warningMsg("请先勾选我已阅读并同意xxx协议!!!");
  proxy.$refs.registerRef.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      //验证验证码是否正确，如果后端返回code不是200return后端给的信息
      const res = await checkSmsCodeAPI({
        phoneNumber: registerForm.value.phoneNumber,
        smsCode: registerForm.value.smsCode,
      });
      if (res.code != 200) return proxy.warningMsg(`${res.msg}`);
      //调用注册接口
      await phoneRegisterAPI(registerForm.value);
      //跳转到账套信息页面，同时把手机号带过去
      router.push(`/InitializeForm?id=${registerForm.value.phoneNumber}`);
      // register(registerForm.value)
      //   .then(res => {
      //     const username = registerForm.value.username
      //     ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + ' 注册成功！</font>', '系统提示', {
      //       dangerouslyUseHTMLString: true,
      //       type: 'success'
      //     })
      //       .then(() => {
      //         router.push('/login')
      //       })
      //       .catch(() => {})
      //   })
      //   .catch(() => {
      //     loading.value = false
      //     if (captchaEnabled) {
      //       getCode()
      //     }
      //   })
    }
  });
}

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      registerForm.value.uuid = res.uuid;
    }
  });
}
// getCode()

let timer = null;
//获取验证码按钮
const giveCode = () => {
  const PHONE = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
  clearInterval(timer);
  if (!registerForm.value.phoneNumber) return proxy.warningMsg("请填写手机号!");
  if (!PHONE.test(registerForm.value.phoneNumber)) {
    return proxy.warningMsg("手机号格式错误!");
  }
  try {
    VcodeShow.value = true;
  } catch {
  } finally {
  }
};

// 用户通过了验证
const success = async (msg) => {
  console.log("成功了");
  VcodeShow.value = false;
  num.value = 60;
  timer = setInterval(() => {
    num.value--;
    if (num.value == 0) clearInterval(timer);
  }, 1000);
  await getCodeAPI({ phoneNumber: registerForm.value.phoneNumber });
};
// 用户点击遮罩层，应该关闭模态框
const close = () => {
  VcodeShow.value = false;
};
// 用户验证失败
const fail = () => {
  console.log("失败了");
  loading.value = false;
};
</script>

<style lang="scss" scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/bglogin.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 40px;
  padding-left: 12px;
}
.inputButton {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  .CodeButton {
    margin-left: 10px;
  }
}
</style>
